An array is a consecutive group of memory locations
that all have the same name and the same type. To refer
to a particular location or element in the array, we
specify the name of the array and the <i>position number</i>
of the particular element in the array.<br>
<spacer width=16 height=1> <a href="^Illustration::c:s0p2"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Figure 4.1</a> shows an integer array called c. This array
contains twelve <i>elements</i>. Any one of these elements
may be referred to by giving the name of the array
followed by the position number of the particular
element in square brackets ([]). The first element in
every array is the <i>zeroth element</i>. Thus, the first element <br>
</page>
<page>
of array <b>c</b> is referred to as <b>c[0]</b>, the second element of
array <b>c</b> is referred to as <b>c[1]</b>, the seventh element of
array <b>c</b> is referred to as <b>c[6]</b>, and, in general, the ith
element of array <b>c</b> is referred to as <b>c[i - 1]</b>. Array names
follow the same conventions as other variable names. <br>
<spacer width=16 height=1>The position number contained within square brackets
is more formally called a <i>subscript</i>. A subscript must be
an integer or an integer expression. If a program uses an
expression as a subscript, then the expression is
evaluated to determine the subscript. For example, if we
assume that variable <b>a</b> is equal to <b>5</b> and that variable <b>b</b>
is equal to <b>6</b>, then the statement<br>
<font size=2><br></font><font size=11><pre>
c[ a + b ] += 2;<p>
</pre></font>
adds <b>2</b> to array element <b>c[ 11 ]</b>. Note that a subscripted
array name is an <i>lvalue</i>--it can be used on the left side
of an assignment.<br>
<spacer width=16 height=1>Let us examine array <b>c</b> in <a href="^Illustration::c:s0p2"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 4.1</a> more closely. The
<i>name</i> of the entire array is <b>c</b>. Its twelve elements are <br>
</page>
<page>
named <b>c[0]</b>, <b>c[1]</b>, <b>c[2]</b>, \xc9 , <b>c[11]</b>. The <i>value</i> of <b>c[0]</b> is <b>-
45</b>, the value of <b>c[1] </b>is <b>6</b>, the value of <b>c[2]</b> is <b>0</b>, the value
of <b>c[7]</b> is <b>62</b>, and the value of <b>c[11]</b> is <b>78</b>. To print the
sum of the values contained in the first three elements
of array c, we would write<br>
<font size=2><br></font><font size=11><pre>
cout << c[ 0 ] + c[ 1 ] + c[ 2 ] << endl;<p>
</pre></font>
To divide the value of the <a href="^Errors::c:s0p0"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>seventh element of array c
by 2 and assign the result to the variable <b>x</b>, we would
write<br>
<font size=2><br></font><font size=11><pre>
x = c[ 6 ] / 2;<p>
</pre></font>
The brackets used to enclose the subscript of an array
are actually an operator in C++. Brackets have the same <br>
</page>
<page>
level of precedence as parentheses. The chart in <a href="^Illustration::c:s0p3"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig.
4.2</a> shows the precedence and associativity of the
operators introduced so far. They are shown top to
bottom in decreasing order of precedence with their
associativity and type. <br>
</page>
<page>
<b>Select the true statement(s). </b><br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. A subscript must be an int or integer expression.">
A subscript can be either of type int or type double. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. The subscript must be contained in square brackets ([]).">
An array element can be referenced by specifying the name of the array followed by a subscript contained in parentheses. <br>
Memory may be reserved for several arrays with a single declaration. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. Arrays can be declared for any data type.">
Arrays can only be of data type int. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="4.4 Examples Using Arrays">
<page>
<font size=18 bold>4.4 Examples Using Arrays</font><hr>
The program in <a href="^Code::c:s0p0"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.3</a> uses a for repetition structure
to initialize the elements of a ten-element integer array
<b>n</b> to zeros, and prints the array in tabular format. The
first output statement displays the column headings for
the columns printed in the subsequent <b>for</b> structure.
Remember that <b>setw</b> specifies the field width in which
the <i>next</i> value is to be output. <br>
<spacer width=16 height=1>The elements of an array can also be initialized in the
array declaration by following the declaration with an
equal sign and a comma-separated list (enclosed in
braces) of <i>initializers</i>. The program in <a href="^Code::c:s0p1"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.4</a> <br>
</page>
<page>
initializes an integer array with ten values and prints the
array in tabular format.<br>
<spacer width=16 height=1>If there are fewer initializers than elements in the array,
the remaining elements are automatically initialized to
zero. For example, the elements of the array <b>n</b> in <a href="^Code::c:s0p0"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig.
4.3</a> could have been initialized to zero with the
declaration <br>
<font size=2><br></font><font size=11><pre>
int n[ 10 ] = { 0 };<p>
</pre></font>
which explicitly initializes the first element to zero and
implicitly <a href="^Errors::c:s0p3"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>initializes the remaining nine elements to
zero because there are fewer initializers than elements
in the array. Remember that automatic arrays are not
implicitly initialized to zero. The programmer must at <br>
</page>
<page>
least initialize the first element to zero for the remaining
elements to be automatically zeroed. The method used
in <a href="^Code::c:s0p0"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.3</a> can be performed repeatedly as a program
executes.<br>
<spacer width=16 height=1>The following array declaration <br>
<font size=2><br></font><font size=11><pre>
int n[ 5 ] = { 32, 27, 64, 18, 95, 14 }; <p>
</pre></font>
would cause a syntax <a href="^Errors::c:s0p2"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>error because there are 6
initializers and only 5 array elements.<br>
<spacer width=16 height=1>If the array size is omitted from a declaration with an
initializer list, the number of elements in the array will
be the number of elements in the initializer list.<a href="^Perform::c:s0p0"> <img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>For
example, <br>
<font size=2><br></font><font size=11><pre>
int n[] = { 1, 2, 3, 4, 5 };<p>
</pre></font>
</page>
<page>
would create a five-element array. <br>
<spacer width=16 height=1>The program in <a href="^Code::c:s0p2"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.5</a> initializes the elements of a
ten-element array <b>s</b> to the integers <b>2, 4, 6, ..., 20</b>, and
prints the array in tabular format. These numbers are
generated by multiplying each successive value of the
loop counter by <b>2</b> and adding <b>2</b>. <br>
<spacer width=16 height=1>The line <br>
<font size=2><br></font><font size=11><pre>
const int arraySize = 10;<p>
</pre></font>
uses the <b>const</b> qualifier to declare a so-called <i>constant</i>
<i>variable</i> <b>arraySize</b> the value of which is <b>10</b>. Constant
variables must be initialized with a constant expression
are also called <i>named constants</i> or <i>read-only variables</i>.
Note that the term "constant variable" is an
oxymoron--a contradiction in terms like "jumbo
shrimp" or "freezer burn." (Please send your favorite
oxymorons to our email address listed in the Preface.
Thanks!)<br>
<spacer width=16 height=1>Constant variables can be placed anywhere a <a href="^Errors::c:s0p4"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>constant
expression is expected. In <a href="^Code::c:s0p2"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.5</a>, constant variable
<b>arraySize</b> is used to specify the size of array <b>s</b> in the
declaration<br>
<font size=2><br></font><font size=11><pre>
int j, s[ arraySize ];<p>
</pre></font>
Using constant variables to specify array sizes makes
programs more <i>scalable</i>. In <a href="^Code::c:s0p2"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.5</a>, the first <b>for</b> loop <br>
</page>
<page>
could fill a 1000-element array by simply changing the
<a href="^Errors::c:s0p5"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>value of <b>arraySize</b> in its declaration from <b>10</b> to <b>1000</b>. If
the constant variable <b>arraySize</b> had not been used, we
would have to change the program in three separate
places to scale the program to handle 1000 array
elements. As programs get larger, this technique
becomes more useful for writing clear programs. <br>
<spacer width=16 height=1>The program in <a href="^Code::c:s0p5"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.8</a> sums the values contained in
the twelve-element integer array <b>a</b>. The statement in the
body of the <b>for</b> loop does the totaling. It is important to
remember that the values being supplied as initializers
<a href="^Engineer::c:s0p0"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>for array <b>a</b> normally would be read into the program <br>
which increments array element six, and so on. Note
that regardless of the number of responses processed in
the survey, only an eleven-element array is required
(ignoring element zero) to summarize the results. If the <br>
</page>
<page>
data contained invalid values such as 13, the program
would attempt to add <b>1</b> to <b>frequency[ 13 ]</b>. This would
be <a href="^Errors::c:s0p6"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>outside the bounds of the array. <i>C++ has no array
bounds checking to prevent the computer from referring
to an element that does not exist</i>. Thus, an executing
<a href="^Debug::c:s0p3"><img src="bckgrnds/icons/dbt_ico.gif" align=sidebar></a>program can walk off either end of an array without
warning. The programmer should ensure that all array
references remain within the bounds of the array. C++
<a href="^Debug::c:s0p2"><img src="bckgrnds/icons/dbt_ico.gif" align=sidebar></a>is an extensible language. In Chapter 8, we will extend
C++ by implementing an array as a user-defined type
<a href="^Portable::c:s0p0"><img src="bckgrnds/icons/port_ico.gif" align=sidebar></a>with a class. Our new array definition will enable us to
perform many operations that are not standard for
C++'s built-in arrays. For example, we will be able to <br>
</page>
<page>
compare arrays directly, assign one array to another,
input and output entire arrays with <b>cin</b> and <b>cout</b>, <a href="^Debug::c:s0p0"><img src="bckgrnds/icons/dbt_ico.gif" align=sidebar></a>
initialize arrays automatically, prevent access to out-of-
range array elements, and change the range of
subscripts (and even their subscript type) so that the
first element of an array is not required to be element 0.<br>
<spacer width=16 height=1>Our next example ( <a href="^Code::c:s0p7"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.10</a>) reads numbers from an
array and graphs the information in the form of a bar
chart or histogram--each number is printed, and then a
bar consisting of that many asterisks is printed beside
<a href="^Errors::c:s0p7"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>the number. The nested <b>for</b> loop actually draws the
bars. Note the use of <b>endl</b> to end a histogram bar.<br>
</page>
<page>
In Chapter 3 we stated that we would show a more
elegant method of writing the dice-rolling program of
Fig. 3.8. The problem was to roll a single six-sided die
6000 times to test whether the random number
generator actually produces random numbers. An array
version of this program is shown in <a href="^Code::c:s0p8"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.11</a>.<br>
<spacer width=16 height=1>To this point we have discussed only integer arrays.
However, arrays may be of any type. We now discuss
<a href="^Debug::c:s0p5"><img src="bckgrnds/icons/dbt_ico.gif" align=sidebar></a>storing character strings in character arrays. So far, the
only string processing capability we introduced is
outputting a string with <b>cout</b> and <b><<</b>. A string such as
<b>"hello"</b> is really an array of characters. Character arrays
have several unique features.<br>
</page>
<page>
A character array can be initialized using a string literal.
For example, the declaration<br>
<font size=2><br></font><font size=11><pre>
char string1[] = "first";<p>
</pre></font>
initializes the elements of array <b>string1</b> to the
individual characters in the string literal <b>"first"</b>. The
size of array <b>string1</b> in the preceding declaration is
determined by the compiler based on the length of the
string. It is important to note that the string <b>"first"</b>
contains five characters <i>plus</i> a special string termination
character called the <i>null character.</i> Thus, array <b>string1</b>
actually contains six elements. The character constant
representation of the null character is <b>'\\0'</b> (backslash
followed by zero). All strings end with this character. A <br>
</page>
<page>
character array representing a string should always be
declared large enough to hold the number of characters
in the string and the terminating null character. <br>
<spacer width=16 height=1>Character arrays also can be initialized with individual
character constants in an initializer list. The preceding
declaration is equivalent to the more tedious form<br>
Because a string is an array of characters, we can access
individual characters in a string directly using array
subscript notation. For example, <b>string1[0]</b> is the
character <b>'f'</b> and <b>string1[3]</b> is the character <b>'s'</b>.<br>
</page>
<page>
We also can input a string directly into a character array
from the keyboard using <b>cin</b> and <b>>></b>. For example, the
declaration <br>
<font size=2><br></font><font size=11><pre>
char string2[ 20 ];<p>
</pre></font>
creates a character array capable of storing a string of
19 characters and a terminating null character. The
statement<br>
<font size=2><br></font><font size=11><pre>
cin >> string2;<p>
</pre></font>
reads a string from the keyboard into <b>string2</b>. Note in
the preceding statement that only the name of the array
is <a href="^Errors::c:s0p8"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>supplied; no information about the size of the array
is provided. It is the programmer's responsibility to <br>
</page>
<page>
ensure that the array into which the string is read is
capable of holding any string the user types at the
keyboard. <b>cin</b> reads characters from the keyboard until
the first whitespace character is encountered--it does
not care how large the array is. Thus, inputting data
with <b>cin</b> and <b>>></b> can insert data beyond the end of the
array (see Section 5.12 for information on preventing
insertion beyond the end of a <b>char</b> array).<br>
<spacer width=16 height=1>A character array representing a null-terminated string
can be output with <b>cout</b> and <b><<</b>. The array <b>string2</b> is
printed with the statement<br>
<font size=2><br></font><font size=11><pre>
cout << string2 << endl;<p>
</pre></font>
</page>
<page>
Note that <b>cout <<</b>, like <b>cin >></b>, does not care how large
the character array is. The characters of the string are
printed until a terminating null character is
encountered.<br>
<spacer width=16 height=1><a href="^Code::c:s0p9"> </a> <a href="^Code::c:s0p9"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 4.12 </a>demonstrates initializing a character array
with a string literal, reading a string into a character
array, printing a character array as a string, and
accessing individual characters of a string. <br>
<spacer width=16 height=1> <a href="^Code::c:s0p9"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 4.12</a> uses a <b>for</b> structure to loop through the
<b>string1</b> array and print the individual characters
separated by spaces. The condition in the <b>for</b> structure,
<b>string1[ i ] != '\\0'</b>, is true while the terminating null
character has not been encountered in the string.<br>
</page>
<page>
Chapter 3 discussed the storage class specifier <b>static</b>. A
<b>static</b> local variable in a function definition exists for <a href="^Perform::c:s0p2"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>
the duration of the program but is only visible in the
function body. <br>
<spacer width=16 height=1>Arrays that are declared <b>static</b> are initialized when the
program is loaded. If a <b>static</b> array is not explicitly
initialized by the programmer, that array is initialized to
</b>with a local array declared <b>static</b> and function
<b>automaticArrayInit</b> with an automatic local array.
Function <b>staticArrayInit </b>is called twice. The <b>static</b>
local array is initialized to zero by the compiler. The <br>
</page>
<page>
function prints the array, adds 5 to each element, and
prints the array again. The second <a href="^Errors::c:s0p9"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>time the function is
called, the <b>static</b> array contains the values stored during
the first function call. Function <b>automaticArrayInit </b>is
also called twice. The elements of the automatic local
array are initialized with the values 1, 2, and 3. The
function prints the array, adds 5 to each element, and
prints the array again. The second time the function is
called, the array elements are re-initialized to 1, 2, and 3
because the array has automatic storage class.<br>
</page>
<page>
<b>Select the true statement(s). </b><br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. Array elements can be initialized in a declaration using an initializer list in braces.">
Array elements cannot be initialized in a declaration. <br>
The keyword const is used to declare a constant variable. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. Arrays of type char can be initialized with initializer lists or with C-style strings.">
Arrays of type char cannot be initialized with initializer lists. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="4.5 Passing Arrays to Functions">
<page>
<font size=18 bold>4.5 Passing Arrays to Functions</font><hr>
To pass an array argument to a function, specify the
name of the array without any brackets. For example, if
array <b>hourlyTemperatures</b> has been declared as<br>
<font size=2><br></font><font size=11><pre>
int hourlyTemperatures[ 24 ];<p>
</pre></font>
the function call statement<br>
<font size=2><br></font><font size=11><pre>
modifyArray( hourlyTemperatures, 24 );<p>
</pre></font>
passes array <b>hourlyTemperatures</b> and its size to
function <b>modifyArray</b>. When passing an array to a
function, the array size is normally passed as well so the
function can process the specific number of elements in
the array (otherwise, we would need to build this <br>
</page>
<page>
knowledge into the called function itself, or worse yet
place the array size in a global variable). In Chapter 8,
when we introduce the <b>Array</b> class, we will build the
size of the array into the user-defined type--every
<b>Array</b> object that we create will "know" its own size.
Thus, when we pass an <b>Array</b> object into a function we
no longer will have to pass the size of the array as an
argument. <br>
<spacer width=16 height=1>C++ automatically passes arrays to <a href="^Perform::c:s0p4"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>functions using
simulated call-by-reference--the called functions can
<a href="^Engineer::c:s0p1"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>modify the element values in the callers' original
arrays. The value of the name of the array is the address
of the first element of the array. Because the starting <br>
</page>
<page>
address of the array is passed, the called function knows
precisely where the array is stored. Therefore, when the
called function modifies array elements in its function
body, it is modifying the actual elements of the array in
their original memory locations. <br>
<spacer width=16 height=1>Although entire arrays are passed simulated call-by-
reference, individual array elements are passed call-by-
value exactly as simple variables are. Such simple
single pieces of data are called <i>scalars</i> or <i>scalar
quantities</i>. To pass an element of an array to a function,
use the subscripted name of the array element as an
argument in the function call. In Chapter 5, we show <br>
</page>
<page>
how to simulate call-by-reference for scalars (i.e.,
individual variables and array elements). <br>
<spacer width=16 height=1>For a function to receive an array through a function
call, the function's parameter list must specify that an
array will be received. For example, the function header
for function <b>modifyArray</b> might be written as<br>
<font size=2><br></font><font size=11><pre>
void modifyArray( int b[], int arraySize )<p>
</pre></font>
indicating that <b>modifyArray</b> expects to receive an
array of integers in parameter b and the number of array
elements in parameter <b>arraySize</b>. The size of the array
is not required between the array brackets. If it is
included, the compiler will ignore it. Because arrays are
passed simulated call-by-reference, when the called <br>
</page>
<page>
function uses the array name <b>b</b>, it will in fact be
referring to the actual array in the caller (array
<b>hourlyTemperatures </b>in the preceding call). In Chapter
5, we introduce other notations for indicating that an
array is being received by a function. As we will see,
these notations are based on the intimate relationship
between arrays and pointers.<br>
<spacer width=16 height=1> <a href="^Practice::c:s0p4"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>Note the strange appearance of the function prototype
for <b>modifyArray
</b><br>
<font size=2><br></font><font size=11><pre>
void modifyArray( int [], int );<p>
</pre></font>
This prototype could have been written<br>
<font size=2><br></font><font size=11><pre>
void modifyArray( int anyArrayName[], int anyVariableName )<p>
</pre></font>
</page>
<page>
but as we learned in Chapter 3, C++ compilers ignore
variable names in prototypes.<br>
<spacer width=16 height=1>Remember, the prototype tells the compiler the number
of arguments and the types of each argument (in the
order in which the arguments are expected to appear).<br>
<spacer width=16 height=1>The program in <a href="^Code::c:s0p11"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.14</a> demonstrates the difference
between passing an entire array and passing an array
element. The program first prints the five elements of
integer array <b>a</b>. Next, <b>a</b> and its size are passed to
function <b>modifyArray</b> where each of <b>a</b>'s elements is
multiplied by 2. Then <b>a</b> is reprinted in <b>main</b>. As the
output shows, the elements of <b>a</b> are indeed modified by
<b>modifyArray</b>. Now the program prints the value of <br>
</page>
<page>
<b>a[3]</b> and passes it to function <b>modifyElement</b>. Function
<b>modifyElement</b> multiplies its argument by 2 and prints
the new value. Note that when <b>a[3]</b> is reprinted in
<b>main</b>, it has not been modified because individual array
elements are passed call-by-value. <br>
<spacer width=16 height=1>There may be situations in your programs in which a
function should not be allowed to modify array
elements. Because arrays are always passed simulated
call-by-reference, modification of values in an array is
difficult to control. C++ provides the type qualifier
<b>const</b> that can be used to prevent modification of array
values in a function. When an array parameter is
preceded by the <b>const</b> qualifier, the elements of the <br>
</page>
<page>
array become constant in the function body, and any
attempt to modify an element of the array in the
function body results in a syntax error. This enables the
programmer to correct a program so it does not attempt
to modify array elements. <br>
<spacer width=16 height=1> <a href="^Code::c:s0p12"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 4.15</a> demonstrates the <b>const</b> <a href="^Errors::c:s0p10"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>qualifier. Function
<b>tryToModifyArray </b>is defined with parameter <b>const int
b[]</b> which specifies that array <b>b</b> is constant and cannot
be <a href="^Engineer::c:s0p2"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>modified. Each of the three attempts by the function
to modify array elements results in the syntax error
<b>"Cannot modify a const object."</b> The <b>const</b> qualifier
Call-by-reference gives called functions the ability to directly access the caller's data. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. Arrays are passed call-by-reference by default. All other types of data are passed-by-value by default.">
Arrays are passed call-by-value by default. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
<i>Sorting</i> data (i.e., placing the data into some particular
order such as ascending or descending) is one of the
most important computing applications. A bank sorts
all checks by account number so that it can prepare
individual bank statements at the end of each month.
Telephone companies sort their lists of accounts by last
name and, within that, by first name to make it easy to
find phone numbers. Virtually every organization must
sort some data and in many cases massive amounts of
data. Sorting data is an intriguing problem which has
attracted some of the most intense research efforts in <br>
</page>
<page>
the field of computer science. In this chapter we discuss
<i><a href="^Perform::c:s0p6"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a></i>the simplest known sorting scheme. In the exercises and
in Chapter 15, we investigate more complex schemes
that yield superior performance. <br>
<spacer width=16 height=1>The program in <a href="^Code::c:s0p13"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.16</a> sorts the values of the ten-
element array <b>a</b> into ascending order. The technique we
use is called the <i>bubble sort</i> or the <i>sinking sort</i> because
the smaller values gradually "bubble" their way upward
to the top of the array like air bubbles rising in water,
while the larger values sink to the bottom of the array.
The technique is to make several passes through the
array. On each pass, successive pairs of elements are
compared. If a pair is in increasing order (or the values <br>
</page>
<page>
are identical), we leave the values as they are. If a pair
is in decreasing order, their values are swapped in the
array.<br>
<spacer width=16 height=1>First the program compares <b>a[ 0 ] </b>to <b>a[ 1 ]</b>, then <b>a[ 1 ]</b>
to <b>a[ 2 ]</b>, then <b>a[ 2 ]</b> to <b>a[ 3 ]</b>, and so on until it
completes the pass by comparing <b>a[ 8 ]</b> to <b>a[ 9 ]</b>.
Although there are 10 elements, only nine comparisons
are performed. Because of the way the successive
comparisons are made, a large value may move down
the array many positions on a single pass, but a small
value may move up only one position. On the first pass,
the largest value is guaranteed to sink to the bottom
element of the array, <b>a[ 9 ]</b>. On the second pass, the <br>
</page>
<page>
second largest value is guaranteed to sink to <b>a[ 8 ]</b>. On
the ninth pass, the ninth largest value sinks to <b>a[ 1 ]</b>.
This leaves the smallest value in <b>a[ 0 ]</b>, so only nine
passes are needed to sort a 10-element array.<br>
<spacer width=16 height=1>The sorting is performed by the nested <b>for</b> loop. If a
swap is necessary, it is performed by the three
assignments<br>
<font size=2><br></font><font size=11><pre>
hold = a[ i ];<p>
a[ i ] = a[ i + 1 ];<p>
a[ i + 1 ] = hold;<p>
</pre></font>
where the extra variable <b>hold</b> temporarily stores one of
the two values being swapped. The swap cannot be
performed with only the two assignments<br>
</page>
<page>
<font size=2><br></font><font size=11><pre>
a[ i ] = a[ i + 1 ];<p>
a[ i + 1 ] = a[ i ];<p>
</pre></font>
If, for example, <b>a[i]</b> is <b>7</b> and <b>a[i + 1]</b> is <b>5</b>, after the first
assignment both values will be <b>5</b> and the value <b>7</b> will be
lost. Hence the need for the extra variable <b>hold</b>.<br>
<spacer width=16 height=1>The chief virtue of the bubble sort is that it is easy to
program. However, the bubble sort runs slowly. This
becomes apparent when sorting large arrays. In the
exercises, we will develop more efficient versions of
the bubble sort and investigate some far more efficient
sorts than the bubble sort. More advanced courses
investigate sorting and searching in greater depth. <br>
</page>
<page>
<b>Select the true statement(s). </b><br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. The bubble sort is inefficient for large arrays.">
The bubble sort is efficient for sorting large arrays. <br>
The maximum number of comparisons needed for the binary search of any sorted array is the exponent for the first power of 2 greater than the number of elements in the array. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. The process is known as searching.">
The process of locating a particular element value in an array is called sorting. <br>
subscripted array, <b>a</b>. The array contains three rows and
four columns, so it is said to be a 3-by-4 array. In
general, an array with <i>m</i> rows and <i>n</i> columns is called
an <i>m-by-n array</i>.<br>
<spacer width=16 height=1>Every element in array <b>a</b> is identified in <a href="^Illustration::c:s0p4"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 4.21</a> by an
element name of the form <b>a[ i ][ j ]; a</b> is the name of the
array, and <b>i</b> and <b>j</b> are the subscripts that uniquely
<a href="^Errors::c:s0p11"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>identify each element in <b>a</b>. Notice that the names of the
elements in the first row all have a first subscript of <b>0</b>;
the names of the elements in the fourth column all have
a second subscript of <b>3</b>. <br>
</page>
<page>
A multiple-subscripted array can be initialized in its
declaration much like a single subscripted array. For
example, a double-subscripted array <b>b[ 2 ][ 2 ]</b> could be
declared and initialized with<br>
<font size=2><br></font><font size=11><pre>
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };<p>
</pre></font>
The values are grouped by row in braces. So, <b>1</b> and <b>2</b>
initialize <b>b[ 0 ][ 0 ]</b> and <b>b[ 0 ][ 1 ]</b>, and <b>3</b> and <b>4</b> initialize
<b>b[ 1 ][ 0 ]</b> and <b>b[ 1 ][ 1 ]</b>. If there are not enough
initializers for a given row, the remaining elements of
that row are initialized to <b>0</b>. Thus, the declaration<br>
declares three arrays, each with two rows and three
columns. The declaration of <b>array1</b> provides six
initializers in two sublists. The first sublist initializes
the first row of the array to the values 1, 2, and 3; and
the second sublist initializes the second row of the array
to the values 4, 5, and 6. If the braces around each
sublist are removed from the <b>array1</b> initializer list, the
compiler automatically initializes the elements of the
first row followed by the elements of the second row. <br>
</page>
<page>
The declaration of <b>array2</b> provides five initializers.
The initializers are assigned to the first row then the
second row. Any elements that do not have an explicit
initializer are initialized to zero automatically, so
<b>array2[ 1 ][ 2 ]</b> is initialized to 0. <br>
<spacer width=16 height=1>The declaration of <b>array3</b> provides three initializers in
two sublists. The sublist for the first row explicitly
initializes the first two elements of the first row to 1 and
2. The third element is automatically initialized to zero.
The sublist for the second row explicitly initializes the
first element to 4. The last two elements are
automatically initialized to zero. <br>
</page>
<page>
The program calls function <b>printArray</b> to output each
array's elements. Notice that the function definition
specifies the array parameter as <b>int a[][ 3 ]</b>. When we
receive a single-subscripted array as an argument to a
function, the array brackets are empty in the function's
parameter list. The size of the first subscript of a
multiple-subscripted array is not required either, but all
subsequent subscript sizes are required. The compiler
uses these sizes to determine the locations in memory
of elements in multiple-subscripted arrays. All array
elements are stored consecutively in memory regardless
of the number of subscripts. In a double-subscripted <br>
</page>
<page>
array, the first row is stored in memory followed by the
second row. <br>
<spacer width=16 height=1>Providing the subscript values in a parameter
declaration enables the compiler to tell the function
how to locate an element in the array. In a double-
subscripted array, each row is basically a single-
subscripted array. To locate an element in a particular
row, the function must know exactly how many
elements are in each row so it can skip the proper
number of memory locations when accessing the array.
Thus, when accessing <b>a[ 1 ][ 2 ]</b>, the function knows to
skip the first row's three elements in memory to get to <br>
</page>
<page>
the second row (row 1). Then, the function accesses the
third element of that row (element 2). <br>
<spacer width=16 height=1>Many common array manipulations use <b>for</b> repetition
structures. For example, the following <b>for</b> structure sets
all the elements in the third row of array <b>a</b> in <a href="^Illustration::c:s0p4"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 4.21</a>
to zero:<br>
<font size=2><br></font><font size=11><pre>
for ( column = 0; column < 4; column++ )<p>
a[ 2 ][ column ] = 0;<p>
</pre></font>
We specified the <i>third</i> row, therefore we know that the
first subscript is always <b>2</b> (<b>0</b> is the first row subscript,
and <b>1</b> is the second row subscript). The <b>for</b> loop varies
only the second subscript (i.e., the column subscript). <br>
</page>
<page>
The preceding <b>for</b> structure is equivalent to the
assignment statements:<br>
<font size=2><br></font><font size=11><pre>
a[ 2 ][ 0 ] = 0;<p>
a[ 2 ][ 1 ] = 0;<p>
a[ 2 ][ 2 ] = 0;<p>
a[ 2 ][ 3 ] = 0;<p>
</pre></font>
The following nested <b>for</b> structure determines the total
of all the elements in array <b>a</b>. <br>
<font size=2><br></font><font size=11><pre>
total = 0;<p>
<p>
for ( row = 0; row < 3; row++ ) <p>
for ( column = 0; column < 4; column++ )<p>
total += a[ row ][ column ];<p>
</pre></font>
</page>
<page>
The <b>for</b> structure totals the elements of the array one
row at a time. The outer <b>for</b> structure begins by setting
<b>row</b> (i.e., the row subscript) to <b>0</b> so the elements of the
first row may be totaled by the inner <b>for</b> structure. The
outer <b>for</b> structure then increments <b>row</b> to <b>1</b>, so the
elements of the second row can be totaled. Then, the
outer <b>for</b> structure increments <b>row</b> to <b>2</b>, so the elements
of the third row can be totaled. The result is printed
when the nested for structure terminates.<br>
<spacer width=16 height=1>The program of <a href="^Code::c:s0p18"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.23</a> performs several other
common array manipulations on 3-by-4 array
<b>studentGrades</b>. Each row of the array represents a
student and each column represents a grade on one of <br>
</page>
<page>
the four exams the students took during the semester.
The array manipulations are performed by four
functions. Function <b>minimum</b> determines the lowest
grade of any student for the semester. Function
<b>maximum</b> determines the highest grade of any student
for the semester. Function <b>average</b> determines a
particular student's semester average. Function
<b>printArray</b> outputs the double-subscripted array in a
neat, tabular format.<br>
<spacer width=16 height=1>Functions <b>minimum</b>, <b>maximum</b>, and <b>printArray</b> each
receive three arguments--the <b>studentGrades</b> array
(called <b>grades</b> in each function), the number of students
(rows of the array), and the number of exams (columns <br>
</page>
<page>
of the array). Each function loops through array <b>grades</b>
using nested for structures. The following nested <b>for</b>
structure is from the function <b>minimum</b> definition:<br>
<font size=2><br></font><font size=11><pre>
for ( i = 0; i < pupils; i++ )<p>
for ( j = 0; j < tests; j++ )<p>
if ( grades[ i ][ j ] < lowGrade )<p>
lowGrade = grades[ i ][ j ];<p>
</pre></font>
The outer for structure begins by setting i (i.e., the
row subscript) to <b>0</b> so the elements of the first row can
be compared to variable <b>lowGrade</b> in the body of the
inner <b>for</b> structure. The inner <b>for</b> structure loops
through the four grades of a particular row and
compares each grade to l<b>owGrade</b>. If a grade is less <br>
</page>
<page>
than <b>lowGrade</b>, <b>lowGrade</b> is set to that grade. The
outer <b>for</b> structure then increments the row subscript to
<b>1</b>. The elements of the second row are compared to
variable <b>lowGrade</b>. The outer <b>for</b> structure then
increments the row subscript to <b>2</b>. The elements of the
third row are compared to variable <b>lowGrade</b>. When
execution of the nested structure is complete,
<b>lowGrade</b> contains the smallest grade in the double-
subscripted array. Function <b>maximum</b> works similarly
to function <b>minimum</b>.<br>
<spacer width=16 height=1>Function <b>average</b> takes two arguments--a single-
subscripted array of test results for a particular student
and the number of test results in the array. When <br>
</page>
<page>
<b>average </b>is called, the first argument is <b>studentGrades[
student ]</b> which specifies that a particular row of the
double-subscripted array <b>studentGrades</b> is to be
passed to <b>average</b>. For example, the argument
<b>studentGrades[ 1 ]</b> represents the four values (a single-
subscripted array of grades) stored in the second row of
the double-subscripted array <b>studentGrades</b>. A
double-subscripted array could be considered an array
with elements that are single-subscripted arrays.
Function <b>average</b> calculates the sum of the array
elements, divides the total by the number of test results,
and returns the floating-point result.<br>
</page>
<page>
<b>Select the true statement(s). </b><br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. Multiple-subscripted arrays can have more than two subscripts.">
Multiple-subscripted arrays always have two subscripts (i.e., two dimensions). <br>
<font size=18>Fig<a href="~audio/Ch04/04fig021.au"><img src="bckgrnds/icons/audio.gif" align=sidebar></a>ure 4.21 - A double-subscripted array with three rows and four columns.<img src="graphics/ch04/fig04021.gif" ></font><br>
</page>
<page>
<font size=18>Figure 4.24 - The 36 possible outcomes of rolling two dice.<img src="graphics/ch04/fig04024.gif" ></font><br>
</page>
<page>
<font size=18>Figure 4.25 - The eight possible moves of the knight.<img src="graphics/ch04/fig04025.gif" ></font><br>
</page>
<page>
<font size=18>Figure 4.26 - The 22 squares eliminated by placing a queen in the upper-left corner.</font><br>
d) A C++ program that initializes the elements of a 15-element array to zero
must contain at least one <b>for</b> statement.<br>
</page>
<page pagename="Exercise 4.7">
e) A C++ program that totals the elements of a double-subscripted array must
contain nested <b>for</b> statements.<br>
<br>
</page>
<page pagename="Exercise 4.8">
<b>Exercise 4.8</b><br>
Write C++ statements to accomplish each of the following:<br>
a) Display the value of the seventh element of character array <b>f</b>.<br>
b) Input a value into element 4 of single-subscripted floating-point array <b>b</b>.<br>
c) Initialize each of the 5 elements of single-subscripted integer array <b>g</b> to <b>8</b>. <br>
d) Total and print the elements of floating-point array <b>c</b> of 100 elements.<br>
e) Copy array <b>a</b> into the first portion of array <b>b</b>. Assume <b>float a[ 11 ], b[ 34 ];
</b><br>
f) Determine and print the smallest and largest values contained in 99-element
floating-point array <b>w</b>.<br>
<br>
</page>
<page pagename="Exercise 4.9">
<b>Exercise 4.9</b><br>
Consider a 2-by-3 integer array <b>t</b>.<br>
a) Write a declaration for <b>t</b>.<br>
b) How many rows does <b>t</b> have?<br>
c) How many columns does <b>t </b>have?<br>
d) How many elements does <b>t</b> have?<br>
e) Write the names of all the elements in the second row of <b>t</b>.<br>
f) Write the names of all the elements in the third column of <b>t</b>.<br>
g) Write a single statement that sets the element of <b>t</b> in row 1 and column 2 to
zero.<br>
h) Write a series of statements that initializes each element of <b>t</b> to zero. Do not
use a repetition structure.<br>
</page>
<page pagename="Exercise 4.9">
i) Write a nested for structure that initializes each element of <b>t</b> to zero. <br>
j) Write a statement that inputs the values for the elements of <b>t</b> from the
terminal.<br>
k) Write a series of statements that determines and prints the smallest value in
array <b>t</b>.<br>
l) Write a statement that displays the elements of the first row of <b>t</b>.<br>
m) Write a statement that totals the elements of the fourth column of <b>t</b>.<br>
n) Write a series of statements that prints the array <b>t</b> in neat, tabular format. List
the column subscripts as headings across the top and list the row subscripts at
the left of each row.<br>
<br>
</page>
<page pagename="Exercise 4.10">
<b>Exercise 4.10</b><br>
Use a single-subscripted array to solve the following problem. A company pays
its salespeople on a commission basis. The salespeople receive $200 per week
plus 9 percent of their gross sales for that week. For example, a salesperson who
grosses $5000 in sales in a week receives $200 plus 9 percent of $5000, or a
total of $650. Write a program (using an array of counters) that determines how
many of the salespeople earned salaries in each of the following ranges (assume
that each salesperson's salary is truncated to an integer amount):<br>
a) $200-$299<br>
b) $300-$399<br>
c) $400-$499<br>
d) $500-$599<br>
<foreign name="answers" url="^Answers::c:s0p8">
</page>
<page pagename="Exercise 4.10">
e) $600-$699<br>
f) $700-$799<br>
g) $800-$899<br>
h) $900-$999<br>
i) $1000 and over<br>
<foreign name="answers" url="^Answers::c:s0p8">
<br>
</page>
<page pagename="Exercie 4.11">
<b>Exercie 4.11</b><br>
The bubble sort presented in <a href="^Code::c:s0p13"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.16 </a>is inefficient for large arrays. Make the
following simple modifications to improve the performance of the bubble sort.<br>
a) After the first pass, the largest number is guaranteed to be in the highest-
numbered element of the array; after the second pass, the two highest numbers
are "in place," and so on. Instead of making nine comparisons on every pass,
modify the bubble sort to make eight comparisons on the second pass, seven on
the third pass, and so on.<br>
b) The data in the array may already be in the proper order or near-proper order,
so why make nine passes if fewer will suffice? Modify the sort to check at the
end of each pass if any swaps have been made. If none has been made, then the <br>
</page>
<page pagename="Exercie 4.11">
data must already be in the proper order, so the program should terminate. If
swaps have been made, then at least one more pass is needed.<br>
<br>
</page>
<page pagename="Exercise 4.12">
<b>Exercise 4.12</b><br>
Write single statements that perform the following single-subscripted array
operations:<br>
a) Initialize the 10 elements of integer array <b>counts</b> to zeros.<br>
b) Add 1 to each of the 15 elements of integer array <b>bonus</b>.<br>
c) Read 12 values for <b>float</b> array <b>monthlyTemperatures</b> from the keyboard.<br>
d) Print the 5 values of integer array <b>bestScores</b> in column format.<br>
<foreign name="answers" url="^Answers::c:s0p7">
<br>
</page>
<page pagename="Exercise 4.13">
<b>Exercise 4.13</b><br>
Find the error(s) in each of the following statements:<br>
Modify the program of <a href="^Code::c:s0p14"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.17</a> so function <b>mode</b> is capable of handling a tie
for the mode value. Also modify function <b>median</b> so the two middle elements
are averaged in an array with an even number of elements.<br>
<br>
</page>
<page pagename="Exercise 4.15">
<b>Exercise 4.15</b><br>
Use a single-subscripted array to solve the following problem. Read in 20
numbers, each of which is between 10 and 100, inclusive. As each number is
read, print it only if it is not a duplicate of a number already read. Provide for the
"worst case" in which all 20 numbers are different. Use the smallest possible
array to solve this problem.<br>
<foreign name="answers" url="^Answers::c:s0p9">
<br>
</page>
<page pagename="Exercise 4.16">
<b>Exercise 4.16</b><br>
Label the elements of 3-by-5 double-subscripted array <b>sales</b> to indicate the order
in which they are set to zero by the following program segment:<br>
<font size=2><br></font><font size=11><pre>
for ( row = 0; row < 3; row++ ) <p>
for ( column = 0; column < 5; column++ )<p>
sales[ row ][ column ] = 0;<p>
</pre></font>
<br>
</page>
<page pagename="Exercise 4.17">
<b>Exercise 4.17</b><br>
Write a program that simulates the rolling of two dice. The program should use
<b>rand</b> to roll the first die, and should use rand again to roll the second die. The
sum of the two values should then be calculated. <i>Note:</i> Since each die can show
an integer value from 1 to 6, then the sum of the two values will vary from 2 to
12 with 7 being the most frequent sum and 2 and 12 being the least frequent
sums. <a href="^Illustration::c:s0p5"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Figure 4.24</a> shows the 36 possible combinations of the two dice. Your
program should roll the two dice 36,000 times. Use a single-subscripted array to
tally the numbers of times each possible sum appears. Print the results in a
tabular format. Also, determine if the totals are reasonable, i.e., there are six
ways to roll a 7, so approximately one sixth of all the rolls should be 7.<br>
11 cout << "The values in the array are:" << endl;<p>
</pre></font>
</page>
<page pagename="Exercise 4.21">
<font size=14><pre>
12 someFunction( a, arraySize );<p>
</pre></font>
<font size=14><pre>
13 cout << endl;<p>
14 return 0;<p>
15 }<p>
16 <p>
17 void someFunction( int b[], int size )<p>
18 {<p>
19 if ( size > 0 ) {<p>
20 someFunction( &b[ 1 ], size - 1 );<p>
21 cout << b[ 0 ] << " ";<p>
22 }<p>
23 }<p>
</pre></font>
<br>
</page>
<page pagename="Exercise 4.22">
<b>Exercise 4.22</b><br>
Use a double-subscripted array to solve the following problem. A company has
four salespeople (1 to 4) who sell five different products (1 to 5). Once a day,
each salesperson passes in a slip for each different type of product sold. Each
slip contains:<br>
a) The salesperson number<br>
b) The product number<br>
c) The total dollar value of that product sold that day<br>
Thus, each salesperson passes in between 0 and 5 sales slips per day. Assume
that the information from all of the slips for last month is available. Write a
program that will read all this information for last month's sales, and summarize
the total sales by salesperson by product. All totals should be stored in the <br>
</page>
<page pagename="Exercise 4.22">
double-subscripted array <b>sales</b>. After processing all the information for last
month, print the results in tabular format with each of the columns representing a
particular salesperson and each of the rows representing a particular product.
Cross total each row to get the total sales of each product for last month; cross
total each column to get the total sales by salesperson for last month. Your
tabular printout should include these cross totals to the right of the totaled rows
and to the bottom of the totaled columns.<br>
<br>
</page>
<page pagename="Exercise 4.23">
<b>Exercise 4.23</b><br>
(<i>Turtle Graphics</i>) The Logo language, which is particularly popular among
personal computer users, made the concept of <i>turtle graphics</i> famous. Imagine a
mechanical turtle that walks around the room under the control of a C++
program. The turtle holds a pen in one of two positions, up or down. While the
pen is down, the turtle traces out shapes as it moves; while the pen is up, the
turtle moves about freely without writing anything. In this problem you will
simulate the operation of the turtle and create a computerized sketchpad as well. <br>
<spacer width=20 height=1>Use a 20-by-20 array <b>floor</b> which is initialized to zeros. Read commands from
an array that contains them. Keep track of the current position of the turtle at all
times and whether the pen is currently up or down. Assume that the turtle always<br>
<foreign name="answers" url="^Answers::c:s0p11">
</page>
<page pagename="Exercise 4.23">
starts at position 0,0 of the floor with its pen up. The set of turtle commands your
program must process are as follows: <img src="graphics/ch04/ex04023.gif" ><br>
<foreign name="answers" url="^Answers::c:s0p11">
</page>
<page pagename="Exercise 4.23">
Suppose that the turtle is somewhere near the center of the floor. The following
"program" would draw and print a 12-by 12-square leaving the pen in the up
position:<br>
<foreign name="answers" url="^Answers::c:s0p11">
</page>
<page pagename="Exercise 4.23">
6<p>
9<br>
As the turtle moves with the pen down, set the appropriate elements of array
<b>floor</b> to <b>1</b>s. When the <b>6</b> command (print) is given, wherever there is a <b>1</b> in the
array, display an asterisk, or some other character you choose. Wherever there is
a zero display a blank. Write a program to implement the turtle graphics
capabilities discussed here. Write several turtle graphics programs to draw
interesting shapes. Add other commands to increase the power of your turtle
graphics language.<br>
<foreign name="answers" url="^Answers::c:s0p11">
<br>
</page>
<page pagename="Exercise 4.24">
<b>Exercise 4.24</b><br>
(<i>Knight's Tour</i>) One of the more interesting puzzlers for chess buffs is the
Knight's Tour problem, originally proposed by the mathematician Euler. The
question is this: Can the chess piece called the knight move around an empty
chessboard and touch each of the 64 squares once and only once? We study this
intriguing problem in depth here.<br>
<spacer width=20 height=1>The knight makes L-shaped moves (over two in one direction and then over one
in a perpendicular direction). Thus, from a square in the middle of an empty
chessboard, the knight can make eight different moves (numbered 0 through 7)
as shown in <a href="^Illustration::c:s0p6"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 4.25</a>.<br>
a) Draw an 8-by-8 chessboard on a sheet of paper and attempt a Knight's Tour
by hand. Put a <b>1</b> in the first square you move to, a <b>2</b> in the second square, a <b>3</b> in <br>
</page>
<page pagename="Exercise 4.24">
the third, etc. Before starting the tour, estimate how far you think you will get,
remembering that a full tour consists of 64 moves. How far did you get? Was
this close to your estimate?<br>
b) Now let us develop a program that will move the knight around a chessboard.
The board is represented by an 8-by-8 double-subscripted array <b>board</b>. Each of
the squares is initialized to zero. We describe each of the eight possible moves in
terms of both their horizontal and vertical components. For example, a move of
type 0 as shown in <a href="^Illustration::c:s0p6"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 4.25</a> consists of moving two squares horizontally to the
right and one square vertically upward. Move 2 consists of moving one square
horizontally to the left and two squares vertically upward. Horizontal moves to
the left and vertical moves upward are indicated with negative numbers. The <br>
</page>
<page pagename="Exercise 4.24">
eight moves may be described by two single-subscripted arrays, <b>horizontal</b> and
<b>vertical</b>, as follows:<br>
<font size=2><br></font><font size=11><pre>
horizontal[ 0 ] = 2<p>
horizontal[ 1 ] = 1<p>
horizontal[ 2 ] = -1<p>
horizontal[ 3 ] = -2<p>
horizontal[ 4 ] = -2<p>
horizontal[ 5 ] = -1<p>
horizontal[ 6 ] = 1<p>
horizontal[ 7 ] = 2<p>
<p>
vertical[ 0 ] = -1<p>
vertical[ 1 ] = -2<p>
vertical[ 2 ] = -2<p>
vertical[ 3 ] = -1<p>
vertical[ 4 ] = 1<p><p>
</pre></font>
</page>
<page pagename="Exercise 4.24">
<font size=2><br></font><font size=11><pre>
vertical[ 5 ] = 2<p>
vertical[ 6 ] = 2<p>
vertical[ 7 ] = 1<p>
</pre></font>
Let the variables <b>currentRow </b>and <b>currentColumn</b> indicate the row and column
of the knight's current position. To make a move of type <b>moveNumber</b>, where
<b>moveNumber</b> is between 0 and 7, your program uses the statements<br>
<font size=2><br></font><font size=11><pre>
currentRow += vertical[ moveNumber ];<p>
currentColumn += horizontal[ moveNumber ];<p>
</pre></font>
Keep a counter that varies from <b>1</b> to <b>64</b>. Record the latest count in each square
the knight moves to. Remember to test each potential move to see if the knight
has already visited that square. And, of course, test every potential move to
make sure that the knight does not land off the chessboard. Now write a program <br>
</page>
<page pagename="Exercise 4.24">
to move the knight around the chessboard. Run the program. How many moves
did the knight make?<br>
c) After attempting to write and run a Knight's Tour program, you have
probably developed some valuable insights. We will use these to develop a
<i>heuristic</i> (or strategy) for moving the knight. Heuristics do not guarantee
success, but a carefully developed heuristic greatly improves the chance of
success. You may have observed that the outer squares are more troublesome
than the squares nearer the center of the board. In fact, the most troublesome, or
inaccessible, squares are the four corners.<br>
Intuition may suggest that you should attempt to move the knight to the most
troublesome squares first and leave open those that are easiest to get to so when <br>
</page>
<page pagename="Exercise 4.24">
the board gets congested near the end of the tour there will be a greater chance of
success.<br>
We may develop an "accessibility heuristic" by classifying each of the squares
according to how accessible they are, and then always moving the knight to the
square (within the knight's L-shaped moves, of course) that is most inaccessible.
We label a double-subscripted array <b>accessibility</b> with numbers indicating from
how many squares each particular square is accessible. On a blank chessboard,
each center square is rated as <b>8</b>, each corner square is rated as <b>2</b>, and the other
squares have accessibility numbers of <b>3</b>, <b>4</b>, or <b>6</b> as follows:<br>
</page>
<page pagename="Exercise 4.24">
<font size=2><br></font><font size=11><pre>
<b>2 3 4 4 4 4 3 2<p>
3 4 6 6 6 6 4 3<p>
4 6 8 8 8 8 6 4<p>
4 6 8 8 8 8 6 4<p>
4 6 8 8 8 8 6 4<p>
4 6 8 8 8 8 6 4<p>
3 4 6 6 6 6 4 3<p>
2 3 4 4 4 4 3 2
</b><p>
</pre></font>
Now write a version of the Knight's Tour program using the accessibility
heuristic. At any time, the knight should move to the square with the lowest
accessibility number. In case of a tie, the knight may move to any of the tied
squares. Therefore, the tour may begin in any of the four corners. (<i>Note:</i> As the
knight moves around the chessboard, your program should reduce the <br>
</page>
<page pagename="Exercise 4.24">
accessibility numbers as more and more squares become occupied. In this way,
at any given time during the tour, each available square's accessibility number
will remain equal to precisely the number of squares from which that square
may be reached.) Run this version of your program. Did you get a full tour?
Now modify the program to run 64 tours, one starting from each square of the
chessboard. How many full tours did you get?<br>
d) Write a version of the Knight's Tour program which, when encountering a tie
between two or more squares, decides what square to choose by looking ahead
to those squares reachable from the "tied" squares. Your program should move
to the square for which the next move would arrive at a square with the lowest
accessibility number.<br>
<br>
</page>
<page pagename="Exercise 4.25">
<b>Exercise 4.25</b><br>
(<i>Knight's Tour: Brute Force Approaches</i>) In <a href="^Exercises::c:s0p38"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 4.24</a> we developed a
solution to the Knight's Tour problem. The approach used, called the
"accessibility heuristic," generates many solutions and executes efficiently.<br>
<spacer width=20 height=1>As computers continue increasing in power, we will be able to solve more
problems with sheer computer power and relatively unsophisticated algorithms.
Let us call this approach "brute force" problem solving.<br>
a) Use random number generation to enable the knight to walk around the chess
board (in its legitimate L-shaped moves, of course) at random. Your program
should run one tour and print the final chessboard. How far did the knight get?<br>
b) Most likely, the preceding program produced a relatively short tour. Now
modify your program to attempt 1000 tours. Use a single-subscripted array to <br>
</page>
<page pagename="Exercise 4.25">
keep track of the number of tours of each length. When your program finishes
attempting the 1000 tours, it should print this information in neat tabular format.
What was the best result?<br>
c) Most likely, the preceding program gave you some "respectable" tours but no
full tours. Now "pull all the stops out" and simply let your program run until it
produces a full tour. (<i>Caution:</i> This version of the program could run for hours
on a powerful computer.) Once again, keep a table of the number of tours of
each length, and print this table when the first full tour is found. How many tours
did your program attempt before producing a full tour? How much time did it
take?<br>
d) Compare the brute force version of the Knight's Tour with the accessibility
heuristic version. Which required a more careful study of the problem? Which <br>
</page>
<page pagename="Exercise 4.25">
algorithm was more difficult to develop? Which required more computer power?
Could we be certain (in advance) of obtaining a full tour with the accessibility
heuristic approach? Could we be certain (in advance) of obtaining a full tour
with the brute force approach? Argue the pros and cons of brute force problem
solving in general.<br>
<br>
</page>
<page pagename="Exercise 4.26">
<b>Exercise 4.26</b><br>
(<i>Eight Queens</i>) Another puzzler for chess buffs is the Eight Queens problem.
Simply stated: Is it possible to place eight queens on an empty chessboard so
that no queen is "attacking" any other, i.e., no two queens are in the same row,
the same column, or along the same diagonal? Use the thinking developed in
<a href="^Exercises::c:s0p38"><img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 4.24</a> to formulate a heuristic for solving the Eight Queens problem.
Run your program. (<i>Hint:</i> It is possible to assign a value to each square of the
chessboard indicating how many squares of an empty chessboard are
"eliminated" if a queen is placed in that square. Each of the corners would be
assigned the value 22, as in <a href="^Illustration::c:s0p7"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 4.26</a>.) Once these "elimination numbers" are
placed in all 64 squares, an appropriate heuristic might be: Place the next queen <br>
</page>
<page pagename="Exercise 4.26">
in the square with the smallest elimination number. Why is this strategy
intuitively appealing?<br>
<br>
</page>
<page pagename="Exercise 4.27">
<b>Exercise 4.27</b><br>
(<i>Eight Queens: Brute Force Approaches</i>) In this exercise you will develop
several brute force approaches to solving the Eight Queens problem introduced
in <a href="^Exercises::c:s0p49"><img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 4.26</a>.<br>
a) Solve the Eight Queens exercise, using the random brute force technique
developed in <a href="^Exercises::c:s0p46"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 4.25</a>.<br>
b) Use an exhaustive technique, i.e., try all possible combinations of eight
queens on the chessboard.<br>
c) Why do you suppose the exhaustive brute force approach may not be
appropriate for solving the Knight's Tour problem?<br>
d) Compare and contrast the random brute force and exhaustive brute force
approaches in general.<br>
</page>
<page pagename="Exercise 4.28">
<b>Exercise 4.28</b><br>
(<i>Knight's Tour: Closed Tour Test</i>) In the Knight's Tour, a full tour occurs when
the knight makes 64 moves touching each square of the chess board once and
only once. A closed tour occurs when the 64th move is one move away from the
location in which the knight started the tour. Modify the Knight's Tour program
you wrote in <a href="^Exercises::c:s0p38"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 4.24</a> to test for a closed tour if a full tour has occurred.<br>
<br>
</page>
<page pagename="Exercise 4.29">
<b>Exercise 4.29</b><br>
(<i>The Sieve of Eratosthenes</i>) A prime integer is any integer that is evenly
divisible only by itself and 1. The Sieve of Eratosthenes is a method of finding
prime numbers. It operates as follows:<br>
a) Create an array with all elements initialized to 1 (true). Array elements with
prime subscripts will remain 1. All other array elements will eventually be set to
zero.<br>
b) Starting with array subscript 2 (subscript 1 must be prime), every time an
array element is found whose value is 1, loop through the remainder of the array
and set to zero every element whose subscript is a multiple of the subscript for
the element with value 1. For array subscript 2, all elements beyond 2 in the
array that are multiples of 2 will be set to zero (subscripts 4, 6, 8, 10, etc.); for<br>
<foreign name="answers" url="^Answers::c:s0p12">
</page>
<page pagename="Exercise 4.29">
array subscript 3, all elements beyond 3 in the array that are multiples of 3 will
be set to zero (subscripts 6, 9, 12, 15, etc.); and so on.<br>
When this process is complete, the array elements that are still set to one indicate
that the subscript is a prime number. These subscripts can then be printed. Write
a program that uses an array of 1000 elements to determine and print the prime
numbers between 1 and 999. Ignore element 0 of the array.<br>
<foreign name="answers" url="^Answers::c:s0p12">
<br>
</page>
<page pagename="Exercise 4.30">
<b>Exercise 4.30</b><br>
(<i>Bucket Sort</i>) A bucket sort begins with a single-subscripted array of positive
integers to be sorted, and a double-subscripted array of integers with rows
subscripted from 0 to 9 and columns subscripted from 0 to n - 1 where n is the
number of values in the array to be sorted. Each row of the double-subscripted
array is referred to as a bucket. Write a function <b>bucketSort</b> that takes an integer
array and the array size as arguments and performs as follows:<br>
a) Place each value of the single-subscripted array into a row of the bucket array
based on the value's ones digit. For example, 97 is placed in row 7, 3 is placed in
row 3, and 100 is placed in row 0. This is called a "distribution pass."<br>
<foreign name="answers" url="^Answers::c:s0p13">
</page>
<page pagename="Exercise 4.30">
b) Loop through the bucket array row-by-row and copy the values back to the
original array. This is called a "gathering pass." The new order of the preceding
values in the single-subscripted array is 100, 3, and 97.<br>
c) Repeat this process for each subsequent digit position (tens, hundreds,
thousands, etc.). <br>
On the second pass, 100 is placed in row 0, 3 is placed in row 0 (because 3 has
no tens digit), and 97 is placed in row 9. After the gathering pass, the order of
the values in the single-subscripted array is 100, 3, and 97. On the third pass,
100 is placed in row 1, 3 is placed in row zero and 97 is placed in row zero (after
the 3). After the last gathering pass, the original array is now in sorted order. <br>
<spacer width=20 height=1>Note that the double-subscripted array of buckets is ten times the size of the
integer array being sorted. This sorting technique provides better performance<br>
<foreign name="answers" url="^Answers::c:s0p13">
</page>
<page pagename="Exercise 4.30">
than a bubble sort, but requires much more memory. The bubble sort requires
space for only one additional element of data. This is an example of the space-
time tradeoff: The bucket sort uses more memory than the bubble sort, but
performs better. This version of the bucket sort requires copying all the data
back to the original array on each pass. Another possibility is to create a second
double-subscripted bucket array and repeatedly swap the data between the two
bucket arrays.<br>
<foreign name="answers" url="^Answers::c:s0p13">
<br>
</page>
<page pagename="Recursion Exercises">
<b>Recursion Exercises</b><br>
</page>
<page pagename="Exercise 4.31">
<b>Exercise 4.31</b><br>
(<i>Selection Sort</i>) A selection sort searches an array looking for the smallest
element in the array. Then, the smallest element is swapped with the first
element of the array. The process is repeated for the subarray beginning with the
second element of the array. Each pass of the array results in one element being
placed in its proper location. This sort performs comparably to the bubble sort--
for an array of <i>n</i> elements, <i>n - 1</i> passes must be made, and for each subarray, <i>n -
1</i> comparisons must be made to find the smallest value. When the subarray being
processed contains one element, the array is sorted. Write recursive function
<b>selectionSort</b> to perform this algorithm.<br>
<br>
</page>
<page pagename="Exercise 4.32">
<b>Exercise 4.32</b><br>
(<i>Palindromes</i>) A palindrome is a string that is spelled the same way forwards
and backwards. Some examples of palindromes are: "radar," "able was i ere i
saw elba," and (if blanks are ignored) "a man a plan a canal panama." Write a
recursive function <b>testPalindrome</b> that returns <b>true</b> if the string stored in the
array is a palindrome, and <b>false</b> otherwise. The function should ignore spaces
and punctuation in the string. <br>
<br>
</page>
<page pagename="Exercise 4.33">
<b>Exercise 4.33</b><br>
(<i>Linear Search)</i> Modify <a href="^Code::c:s0p15"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.19</a> to use recursive function <b>linearSearch</b> to
perform a linear search of the array. The function should receive an integer array
and the size of the array as arguments. If the search key is found, return the array
subscript; otherwise, return 1.<br>
<foreign name="answers" url="^Answers::c:s0p14">
<br>
</page>
<page pagename="Exercise 4.34">
<b>Exercise 4.34</b><br>
(<i>Binary Search</i>) Modify the program of <a href="^Code::c:s0p16"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.20</a> to use a recursive function
<b>binarySearch</b> to perform the binary search of the array. The function should
receive an integer array and the starting subscript and ending subscript as
arguments. If the search key is found, return the array subscript; otherwise,
return 1.<br>
<br>
</page>
<page pagename="Exercise 4.35">
<b>Exercise 4.35</b><br>
(<i>Eight Queens</i>) Modify the Eight Queens program you created in <a href="^Exercises::c:s0p49"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 4.26</a>
to solve the problem recursively. <br>
<br>
</page>
<page pagename="Exercise 4.36">
<b>Exercise 4.36</b><br>
(<i>Print an array</i>) Write a recursive function <b>printArray</b> that takes an array and
the size of the array as arguments and returns nothing. The function should stop
processing and return when it receives an array of size zero.<br>
<foreign name="answers" url="^Answers::c:s0p15">
<br>
</page>
<page pagename="Exercise 4.37">
<b>Exercise 4.37</b><br>
(<i>Print a string backwards</i>) Write a recursive function <b>stringReverse </b>that takes a
character array containing a string as an argument, prints the string backwards,
and returns nothing. The function should stop processing and return when the
terminating null character is encountered.<br>
<br>
</page>
<page pagename="Exercise 4.38">
<b>Exercise 4.38</b><br>
(<i>Find the minimum value in an array</i>) Write a recursive function
<b>recursiveMinimum</b> that takes an integer array and the array size as arguments
and returns the smallest element of the array. The function should stop
processing and return when it receives an array of 1 element.<br>